<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 奖品列表
     */
    public function getRewardList(){
        $list = Db::name("reward")->where('deletetime',null)->select();
        $user = $this->auth->getUser();
        $re_data['list'] = $list;
        $re_data['reward_sum'] = $user->reward_sum;
        $this->success("奖品列表",$re_data);
    }
    public function getRewardLogList(){

    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 抽奖
     */
    public function getAward(){
        $user = $this->auth->getUser();
       //echo  $user->reward_sum;
        //$user_data = Db::name("user")->where(['id'=>$user->id])->find();
        if($user->reward_sum < 1){
            $this->error("您无抽奖次数");
        }
        $sum_probability = Db::name("reward")->where('deletetime',null)->sum('probability');
        $probability = mt_rand(1,$sum_probability);
        $list = Db::name("reward")->where('deletetime',null)->select();
        $sum_gl = 0;
        foreach ($list as $k=>$v){
            $sum_gl += $v['probability'];
            if($probability <= $sum_gl){
                $in_array['reward_id'] = $v['id'];
                $in_array['name'] = $v['name'];
                $in_array['image'] = $v['image'];
                $in_array['user_id'] = $user->id;
                $in_array['createtime'] = time();
                $in_id = Db::name("rewardlog")->insertGetId($in_array);
                if($in_id > 0){
                    Db::name("user")->where(['id'=>$user->id])->setDec("reward_sum");
                    $this->success('成功',$v);
                    break;
                }else{
                    $this->error("失败");
                }
            }
        }
        $this->error("失败");
    }
    public function getAwardLog(){
        $page = $this->request->post("page", 1);
        $per_page = $this->request->post("per_page", 10);

        $user = $this->auth->getUser();
        $where['user_id'] = $user->id;

        $config['page'] = $page;
        $list = Db::name("rewardlog")->where($where)->paginate($per_page,false,$config);;

        $this->success('获取成功', $list);
    }
}
